﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;
using CE.InputOut;


public partial class car_insurance_results_new : MySessionBasePage
{
    int _currentRow = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("login.aspx");
            }
        }
        else
        {
            Response.Redirect("login.aspx");
        }


        if (Session[General.CarId] == null || Session[General.CarPolicyId] == null)
        {
            string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive").ToString();

            Response.Redirect("~/car-insurance/");

        }
        else
        {
            hplCarResults.NavigateUrl = "";
        }

        if (Session[General.IsCarRestoreResult] != null)
        {
            hplProfile.NavigateUrl = "";
            hplCarDetails.NavigateUrl = "";
            btnBack.Visible = false;
            //ibtRunNewQuote.Visible = true;
            btnNewQuote.Visible = true;
            imgbtnBack.Visible = false;

            lblNoMatchText.Text = "We can’t find you an online quote.";

            imgbtnCompare2.Visible = false;
            imgbtnCompare.Visible = false;
            imgup.Visible = false;
            imgdown.Visible = false;
        }
        else
        {
            btnBack.Visible = true;
            //ibtRunNewQuote.Visible = false;
            btnNewQuote.Visible = false;
            imgbtnBack.Visible = true;

        }



        if (!Page.IsPostBack)
        {
            lblYrofManufacture.Text = "0";


            #region Validation Effect
            divUserRefDetail.Visible = false; //Sakthi

            #endregion

            Session[CE.Global.General.CarResultId] = null;

            if (Session[General.IsCarRestoreResult] != null)
            {
                divSummaryBox.Visible = true;
                divFormSelection.Visible = false;
                imgbtnBack.Visible = false;

                imgbtnCompare.Visible = true;
                imgbtnCompare2.Visible = true;
                imgup.Visible = true;
                imgdown.Visible = true;
            }
            else
            {
                divSummaryBox.Visible = false;
                divFormSelection.Visible = true;
                imgbtnBack.Visible = true;

            }

            ShowQuoteSummary();

            if (!CheckViewCount())
            {
                imgbtnCompare.Visible = false;
                imgbtnCompare2.Visible = false;
                btnBack.Visible = false;
                imgup.Visible = false;
                imgdown.Visible = false;

                divMessage.Visible = true;
                lblMessage.Visible = true;
                imgInstantBuy.Visible = false;
                imgInstantBuy.ImageUrl = "";
                lblMessage.Text = "<br />Due to speed optimization reasons, each user is restricted to 5 quotes per day.<br />Please visit us tomorrow.";
                return;
            }
            else
            {

                divMessage.Visible = false;
                lblMessage.Visible = false;
                imgInstantBuy.ImageUrl = "~/images/bg/heading_buydirect.png";

                Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());

                if (ViewState["SortOrder"] == null)
                {
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                if (ViewState["SortExpression"] == null)
                {
                    ViewState["SortExpression"] = "";
                }

                if (Request.Params["sortby"] != null)
                {
                    int _sortBy = 0;
                    if (Int32.TryParse(Request.Params["sortby"].ToString(), out _sortBy))
                    {
                        string _sortExpress = "";
                        string _sortOrder = "";

                        if (_sortBy == 0)
                        {
                            _sortExpress = "AnnualPremium";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 1)
                        {
                            _sortExpress = "Excess";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 2)
                        {
                            _sortExpress = "CXCoverTypeId";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 3)
                        {
                            _sortExpress = "PolicyHolder";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 4)
                        {
                            _sortExpress = "MedicalExpense";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 5)
                        {
                            //_sortExpress = "CashAllowance";
                            _sortExpress = "PersonnalEffectsLoss";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 6)
                        {
                            _sortExpress = "CarReplacement";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 7)
                        {
                            _sortExpress = "MonthlyPremiumAmount";
                            _sortOrder = " ASC";
                        }
                        else
                        {
                            _sortExpress = "Excess";
                            _sortOrder = " ASC";
                        }

                        ViewState["SortExpression"] = _sortExpress;
                        if (_sortOrder == " ASC")
                            ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                        else
                            ViewState["SortOrder"] = SortDirection.Descending.ToString();
                    }
                    else
                    {
                        ViewState["SortExpression"] = "AnnualPremium";
                        //ViewState["SortOrder"] = " ASC";
                        ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                    }
                }
                else
                {
                    ViewState["SortExpression"] = "AnnualPremium";
                    //ViewState["SortOrder"] = " ASC";
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                //Sakthi on 27 Apr 2011 - Start
                if (Convert.ToInt32(lblYrofManufacture.Text) >= CE.Global.General.GetUTCDateTime().Year - 10)
                {
                    CalculatePremium();
                    ResultsQuotesDataBind();
                    //LoadNoMatchCoverType(10);
                }
                else
                {
                    //LoadNoMatchCoverType(20);
                    ClearCarInsuranceTempResult();
                    gvCarResult.Visible = false;
                    bool isSubmitted = GetReferenceUser(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt64(Session[CE.Global.General.CarId].ToString()), "CI");
                    divHeadingbuydirect.Visible = false;
                    divUserRefDetail.Visible = true;

                    imgbtnCompare.Visible = false;
                    imgbtnCompare2.Visible = false;
                    btnBack.Visible = false;
                    imgup.Visible = false;
                    imgdown.Visible = false;

                    if (isSubmitted)
                    {
                        divNoMatchFound.Visible = false;
                        //divNoInstantMatchFound.Visible = true;
                        Response.Redirect("offline-quote.aspx");
                    }
                    else
                    {
                        if (CheckMailSendCount())
                        {
                            if (CheckOfflineCommencementDate())
                            {
                                divNoMatchFound.Visible = false;
                                //divNoInstantMatchFound.Visible = true;
                                Response.Redirect("offline-quote.aspx");
                            }
                            else
                            {
                                divNoMatchFound.Visible = true;
                                //divNoInstantMatchFound.Visible = false;

                            }

                        }
                        else
                        {
                            divNoMatchFound.Visible = true;
                            //divNoInstantMatchFound.Visible = false;
                        }
                    }
                }
                //ResultsQuotesDataBind();
                //Sakthi on 27 Apr 2011 - End
                LogUserViewedHistory();

                //Popup
                txtFullName.Text = Session[General.UserName].ToString();
                txtMobileNo.PhoneNo = Session[General.UserPhoneNo].ToString();
                txtEmail.Text = Session[General.UserEmail].ToString();

                inputCallMeMakeModel.Value = lblCarMakemodel.Text;
            }
        }
    }

    private bool GetReferenceUser(Int64 UserId, Int64 CarId, string ProductType)
    {
        bool isSubmitted = false;


        //user/viewresulthistory.aspx

        ReferenceUser _referenceuser = new ReferenceUser();
        ReferenceUserDB _referenceuserdb = new ReferenceUserDB();
        _referenceuser = _referenceuserdb.GetReferenceUser(UserId, CarId, ProductType);

        if (_referenceuser != null)
        {
            isSubmitted = true;
        }

        return isSubmitted;
    }

    private bool CheckOfflineCommencementDate()
    {
        bool isDateValid = true;
        DateTime dtCommencement = Convert.ToDateTime(lblCommencementdate.Text);

        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCINoMatchFoundCommencementDaysLimit]";

        SortedList _spList = new SortedList();
        _spList.Add("@CommencementDate", dtCommencement);

        DataTable _dtResult = _db.GetDataTableBySP(_spName, _spList);

        Int32 _retValue = 0;
        if (_dtResult.Rows.Count > 0)
        {
            _retValue = Convert.ToInt32(_dtResult.Rows[0]["isValid"].ToString());
        }

        if (_retValue == 0)
        {
            isDateValid = false;
        }

        return isDateValid;
    }

    private void ShowQuoteSummary()
    {
        CarDetail _cardetail = new CarDetail();
        CarPolicy _carpolicy = new CarPolicy();

        CarDetailDB _cardetaildb = new CarDetailDB();
        CarPolicyDB _carpolicydb = new CarPolicyDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        _cardetail = _cardetaildb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), Convert.ToInt64(Session[General.UserId].ToString()));

        _profile = _profiledb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));

        if (_profile != null && _cardetail != null)
        {
            //Update User Profile
            _cardetail.Info10 = _profile.SurName.ToString();
            if (_profile.FirstName.Length > 0)
            {
                _cardetail.Info10 += " " + _profile.FirstName;
            }
            _cardetail.Info11 = _profile.Gender.ToString();
            _cardetail.Info12 = _profile.DOB.ToString("dd-MMM-yyyy");
            _cardetail.Info13 = _profile.Occupation.ToString();
            _cardetail.Info14 = _profile.JobNature.ToString();
            _cardetail.Info15 = _profile.MaritalStatus.ToString();
            _cardetail.Info16 = _profile.YearDriveSg.ToString();
        }

        _cardetaildb.Insert(_cardetail);

        _carpolicy = _carpolicydb.GetCarPolicy(Convert.ToInt64(Session[General.CarId].ToString()), Convert.ToInt64(Session[General.UserId].ToString()));

        if (_cardetail != null && _carpolicy != null)
        {
            if (_cardetail.CarMakeId == 9999 && _cardetail.CarModelId == 9999)
            {
                btnBack.Visible = false;
                //btnNoMatchBack.Visible = true;
                lblRMessage.Text = "Result: No Instant Matches Found!";
                //divNoMatchFound.Visible = false;
                //divNoInstantMatchFound.Visible = true;
            }
            else
            {
                //ibtBack.Visible = false;
                //ibtNoMatchBack.Visible = true;
                //divNoMatchFound.Visible = false;
                //divNoInstantMatchFound.Visible = true;
            }
            lblYrofManufacture.Text = _cardetail.ManufactYear.ToString();
            lblYrofRegister.Text = _cardetail.RegYear.ToString();
            lblYrofRegisterTop.Text = _cardetail.RegYear.ToString();

            lblCarMakemodel.Text = _cardetail.MakeModelDesc;
            lblCarMakemodelTop.Text = _cardetail.MakeModelDesc;
            if (lblCarMakemodelTop.Text.Length > 40)
            {
                lblCarMakemodelTop.Font.Size = new FontUnit(8.0d);
                lblCarMakemodelTop.ToolTip = _cardetail.MakeModelDesc;
            }

            lblOffpeakvehile.Text = _cardetail.IsPeak ? "Yes" : "No";

            if (_carpolicy.NCDPercent == -1)
            {
                lblNCDvalue.Text = "0%";
            }
            else
            {
                lblNCDvalue.Text = _carpolicy.NCDPercent.ToString() + "%";
            }

            lblAppNCDvalue.Text = _carpolicy.Info1.ToString() + "%";
            lblAppNCDvalueTop.Text = _carpolicy.Info1.ToString() + "%";
            lblAnyclaim.Text = _carpolicy.IsClaimLastThreeYear ? "Yes" : "No";
            lblOffenceDriving.Text = _carpolicy.IsOffDriveCom ? "Yes" : "No";
            lblAddDriver.Text = _carpolicy.IsAddDriver ? "Yes" : "No";
            lblCommencementdate.Text = _carpolicy.CoverageCommenceDate.ToString("dd-MMM-yyyy");
            lblCommencementdateTop.Text = _carpolicy.CoverageCommenceDate.ToString("dd-MMM-yyyy");


        }

        _profile = null;
        _profiledb = null;
        _cardetail = null;
        _cardetaildb = null;
        _carpolicy = null;
        _carpolicydb = null;
    }

    private bool CheckViewCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCarInsuranceResultViewCountByDateUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue > 0;
    }

    private bool CheckMailSendCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCINoMatchFoundCountByMailSendStatus]";

        SortedList _spList = new SortedList();
        _spList.Add("@ProductType", "CI");

        DataTable _dtResult = _db.GetDataTableBySP(_spName, _spList);

        Int32 _retValue = 0;
        if (_dtResult.Rows.Count > 0)
        {
            _retValue = Convert.ToInt32(_dtResult.Rows[0]["MailSendCount"].ToString());
        }
        //return _retValue < 12;
        return _retValue < 1;
    }

    private bool CheckFirstTimeQuote()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocAutoEmailFirstQuoteInsertUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        _spList.Add("@EmailType", 100);
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue == 1;
    }

    //Old One
    private bool SendMailFirstQuoteToUser()
    {
        bool _retVal = false;
        //MyMailManager _mailMgr = new MyMailManager();
        string _emailTo = Session[CE.Global.General.UserEmail].ToString();
        string _customername = Session[CE.Global.General.UserName].ToString();
        string _emailSubject = "First Car Insurance Quote - " + CE.Global.General.GetUTCDateTime().ToString();
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + _customername + ", <br /><br />Thank you for using CompareXpress for the first time.";
        _mailBody += "<br /><br />You are able to view this quote through our Members Area by clicking on the link below. <br /><br /> <a href='http://www.comparexpress.com' target='_blank'>http://www.comparexpress.com</a>.";
        _mailBody += "<br /><br /> Enter your Email and Password to login to the Members Area, located on the top right of the page.";
        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@comparexpress.com'>support@comparexpress.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your CompareXpress Team<br/>Customer Support - SG/International";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
        if (MyMailManager.SendCRMMessage(_emailTo, _emailSubject, _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private void ClearCarInsuranceTempResult()
    {
        MyDatabase _db = new MyDatabase();

        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);
    }

    private Int32 CalculatePremium()
    {
        ClearCarInsuranceTempResult();

        MyDatabase _db = new MyDatabase();

        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());

        Int32 _result = 0;

        if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
        {
            if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationLiberty]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationEtiqa]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationHsbc]", _sPara);
            //else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
            //    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationRSA]", _sPara);
        }
        else if (Session[CE.Global.General.AgentId] != null &&
                 Session[CE.Global.General.ProviderCompanyId] != null)
        {
            if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationLiberty]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationEtiqa]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationHsbc]", _sPara);
            //else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
            //    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationRSA]", _sPara);
        }
        else
        {
            _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);
        }
        return _result;
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        //Sakthi on 15 Feb 2011
        //_userviewdb.LogViewedHistory("CI", Request, "Car Insurance results.");
        _userviewdb.LogResultViewedHistory("CI", Request, "Car Insurance results.");
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        string _strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            _strSort = " ASC";
        }
        else
        {
            _strSort = " DESC";
        }
        dv.Sort = ViewState["SortExpression"].ToString() + _strSort;
        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    private bool SendMailToUser()
    {
        bool _retVal = false;
        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive");
        //if (_strCXLive == "2")
        //{
        //if (CheckFirstTimeQuote())
        //{
        //MyMailManager _mailMgr = new MyMailManager();

        string[] fileList = new string[1];
        fileList[0] = GenerateGridResultPDF();
        string _emailTo = Session[General.UserEmail].ToString();
        string _customername = Session[General.UserName].ToString();
        string _emailSubject = "Your CompareXpress Car Insurance Quote - " + CE.Global.General.GetUTCDateTime().ToString();
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + _customername + "<br /><br />Thank you for using CompareXpress Car Insurance Comparison Engine.";
        _mailBody += "<br /><br />Please find enclosed in PDF a copy of your earlier quote. You are also able to view this quote through our Members Area by clicking on the link below.";
        _mailBody += "<br /><br /><a href='http://www.comparexpress.com' target='_blank'>http://www.comparexpress.com</a>.";
        _mailBody += "<br /><br />Enter your Email and Password to login to the Members Area, located on the top right of the page.";

        Account _account = new Account();
        AccountDB _accountdb = new AccountDB();
        _account = _accountdb.GetAccount(Convert.ToInt64(Session[General.UserId].ToString()));
        if (_account != null)
        {
            //if (!IsExistingUser)
            //{
            _mailBody += "<br /><br /> User Name : " + Session[General.UserEmail].ToString();
            _mailBody += "<br /> Password : " + _account.AuthCode;
            //}
        }
        _mailBody += "<br /><br />Once you log in, you can view your Car Insurance quotes and purchase directly from insurer.";

        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@comparexpress.com'>support@comparexpress.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your CompareXpress Team<br/>Customer Support - SG/International";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
        if (MyMailManager.SendCRMMessageWithAttachment(_emailTo, _emailSubject, _mailBody, fileList))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }
        //}
        //else
        //{
        //    _retVal = true;
        //}
        //}
        //else
        //{
        //    _retVal = true;
        //}

        return _retVal;
    }

    private bool SendMailToUserNEW()
    {
        CE.User.Profile usrprofile = new Profile();
        ProfileDB usrprofiledb = new ProfileDB();

        usrprofile = usrprofiledb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));

        string userfirstname = "";

        if (usrprofile != null)
        {
            userfirstname = usrprofile.FirstName;
        }

        bool _retVal = false;
        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive");

        string _emailTo = Session[General.UserEmail].ToString();
        string _customername = Session[General.UserName].ToString();
        string _emailSubject = "Your Car Insurance Quotes on CompareXpress";
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

        _mailBody = "<body class='email_body'>";
        _mailBody += "<style type='text/css'>";
        _mailBody += ".email_body {background:white;margin:0; padding:0; color:#4c4c4c; font-family:Arial, Helvetica, sans-serif; font-size:0.85em;}";
        _mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
        _mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
        _mailBody += "#email_body {width:100%; text-align: left !important;} ";
        _mailBody += ".email_pad10px {padding:10px;} ";
        _mailBody += ".email_results td {width:33%;} ";
        _mailBody += "</style>";
        _mailBody += "<center>";

        _mailBody += "<table cellpadding='0' cellspacing='0' border='0' style='padding:20px;' width='600'>";
        _mailBody += "<tr><td width='360'><a href='http://www.comparexpress.com/car-insurance/login.aspx' target='_blank'><img src='" + _currentDomainUrl + "/images/email/header_quote.png' width='596' height='187' alt='CompareXpress' border='0' /></a></td></tr>";
        //_mailBody += "<tr><td style='padding-left:45px; padding-right:45px;'><strong>Dear " + Session[General.UserName].ToString() + ",</strong><br/><br/>";
        _mailBody += "<tr><td style='padding-left:45px; padding-right:45px;'><strong>Dear " + userfirstname + ",</strong><br/><br/>";
        _mailBody += "Thank you for using CompareXpress Car Insurance Comparison Engine:<br/><br/>";
        _mailBody += "Please find below a copy of your requested quote.<br/><br/>";

        DataView dvResults = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);

        _mailBody += "<table cellpadding='5' cellspacing='0' border='0' width='546px' class='table_details'>";

        string CITempResultId = inputCarResultId.Value;
        dvResults.RowFilter = " CITempResultId in (" + CITempResultId + ")";

        DataTable dtResults = dvResults.ToTable();


        if (dtResults.Rows.Count > 0)
        {
            string _providercompanyid = dtResults.Rows[0]["providercompanyid"].ToString();
            //logo
            string logourl = "/images/public/logo/";
            if (_providercompanyid == "23")
            {
                logourl += "hsbc.png";
            }
            else if (_providercompanyid == "29")
            {
                 logourl += "liberty.png";
            }
            else if (_providercompanyid == "30")
            {
                logourl += "etiqa.png";
            }

            _mailBody += "<tr>";
            _mailBody += "<td width='45%'></td>";
            _mailBody += "<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'><img src='" + _currentDomainUrl + logourl + "' width='130' style='padding:3px;'/></td>";
            _mailBody += "</tr>";

            string insurername = dtResults.Rows[0]["InsurerName"].ToString();

            if (dtResults.Rows[0]["providercompanyid"].ToString() == "23" || dtResults.Rows[0]["providercompanyid"].ToString() == "30")
            {
                insurername = insurername + " Insurance";
            }

            //insurer name
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Insurer</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5; color:white;'><strong>" + insurername + "</strong></td>";
            _mailBody += "</tr>";

            //premium
            _mailBody += "<tr>";
            _mailBody += "<td align='left' style='background:#d5d5d5' ><strong>Price</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5; color:black; font-size:20px;'><strong>" + String.Format("${0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</strong></td>";
            _mailBody += "</tr>";

            float _fMonthlyPremiumAmount = Convert.ToSingle(dtResults.Rows[0]["MonthlyPremiumAmount"].ToString());
            string monthlyInstallment = "";

            if (_fMonthlyPremiumAmount > 0.0f)
            {
                string _monthlyPremiumAmount = String.Format("${0:0,0.00}", _fMonthlyPremiumAmount);

                monthlyInstallment = _monthlyPremiumAmount + "/mth<br/>";

                if (_providercompanyid == "29")
                {
                    monthlyInstallment += "<br/># Citi card only";
                }
                else if (_providercompanyid == "23")
                {
                    monthlyInstallment += "<br/># HSBC or OCBC card only";
                }

            }
            else
            {
                monthlyInstallment = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }

            //installment
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Monthly Installments <br/>12-mth 0% Interest Free</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + monthlyInstallment + "</td>";
            _mailBody += "</tr>";

            //Excess (named drivers) 
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>Excess </strong> (named drivers)</td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + String.Format("${0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["excess"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //Workshop Plan
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Workshop Plan</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + dtResults.Rows[0]["PlanName"].ToString() + "</td>";
            _mailBody += "</tr>";

            //Personal Accident
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Personal Accident</strong> (insured) </td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + String.Format("${0:#,0}", Convert.ToSingle(dtResults.Rows[0]["PolicyHolder"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //Personal Accident (each passenger)
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>Personal Accident</strong> (each passenger) </td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + String.Format("${0:#,0}", Convert.ToSingle(dtResults.Rows[0]["PassengerEach"].ToString())) + "</td>";
            _mailBody += "</tr>";

            int _MedicalExpense = Convert.ToInt32(dtResults.Rows[0]["MedicalExpense"].ToString());
            string medicalExpense = "";

            if (_MedicalExpense == 0)
            {
                medicalExpense = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            else
            {
                medicalExpense = String.Format("${0:#,0}", Convert.ToSingle(_MedicalExpense.ToString()));
            }

            //Medical Expense
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Medical Expense</strong> (each passenger) </td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + medicalExpense + "</td>";
            _mailBody += "</tr>";

            bool _IsPersonnalEffectsLoss = Convert.ToBoolean(dtResults.Rows[0]["IsPersonnalEffectsLoss"].ToString());
            int _LossPE = Convert.ToInt32(dtResults.Rows[0]["PersonnalEffectsLoss"].ToString());
            string lossPE = "";

            if (!_IsPersonnalEffectsLoss)
            {
                lossPE = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            else
            {
                lossPE = String.Format("${0:#,0}", Convert.ToSingle(_LossPE.ToString()));
            }

            //Loss of Personal Effects
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Loss of Personal Effects</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + lossPE + "</td>";
            _mailBody += "</tr>";

            string _CarReplace = dtResults.Rows[0]["CarReplacement"].ToString();
            bool _IsCarReplace = Convert.ToBoolean(dtResults.Rows[0]["IsCarReplacement"].ToString());
            bool _IsTranspoAllowance = Convert.ToBoolean(dtResults.Rows[0]["isCashAllowance"].ToString());
            string _strTranspoAllowance = Convert.ToString(dtResults.Rows[0]["CashAllowance"].ToString());
            string _strMaxTranspoAllowanceDays = Convert.ToString(dtResults.Rows[0]["MaxCashAllowanceDays"].ToString());
            string lossUse = "";

            if (_IsCarReplace)
            {
                lossUse = "Courtesy Car <br/>" + "max " + _CarReplace.ToString() + " day(s)";
            }
            else
            {
                if (_IsTranspoAllowance)
                {
                    lossUse = "Transport Allowance<br/> S$" + _strTranspoAllowance + "/day <br/> max " + _strMaxTranspoAllowanceDays + " day(s)";
                }
                else
                {
                    lossUse = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
                }

            }

            //Loss of Use (Benefit) 
            _mailBody += "<tr>";
            _mailBody += "<td><strong>Loss of Use</strong> (Benefit)</td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + lossUse + "</td>";
            _mailBody += "</tr>";


            string viewworkshops = "";

            if (_providercompanyid == "29")
            {
                viewworkshops = "<a href='http://www.libertyinsurance.com.sg/pdf/PWS%20Nov05.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            }
            else if (_providercompanyid == "30")
            {
                viewworkshops = "<a href='" + _currentDomainUrl + "/policy_docs/Etiqa/Etiqa - AWS Listing.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            }
            else
            {
                viewworkshops = "<a href='" + _currentDomainUrl + "/policy_docs/HSBC/HSBCworkshops.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            }

            //View Workshops
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>View Workshops</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + viewworkshops + "</td>";
            _mailBody += "</tr>";


            string _policyId = dtResults.Rows[0]["NInfo1"].ToString();

            ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
            ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

            _policydoc = _policydocdb.GetProviderPolicyDocument(Convert.ToInt64(_policyId));

            string docurl = _currentDomainUrl + _policydoc.UploadPath.Remove(0,1);
            string viewpolicywordings = "<a href='" + docurl + "' ><img src='" + _currentDomainUrl + "/images/icon/pdf.png'  alt='policy wordings' width='23' alt='NA' border='0'/></a>";

            //View Policy Wordings
            _mailBody += "<tr>";
            _mailBody += "<td><strong>View Policy Wordings</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + viewpolicywordings + "</td>";
            _mailBody += "</tr>";

            if (_providercompanyid == "23")
            {
                string endorsementlink = "";

                int _coverid = Convert.ToInt32(dtResults.Rows[0]["CXCoverTypeId"].ToString());

                if (_coverid == 2 || _coverid == 6) //classic
                {
                    endorsementlink = _currentDomainUrl + "/policy_docs/HSBC/PCIClassicPlan.pdf";
                }
                else
                {
                    endorsementlink = _currentDomainUrl + "/policy_docs/HSBC/PCIPremierPlan.pdf";
                }


                string viewendorsements = "<a href='" + endorsementlink + "' target='_blank' id='lnkendorse'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' width='23' alt='NA' border='0' /></a>";

                //View Policy Endorsements
                _mailBody += "<tr>";
                _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>View Endorsements</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5' >" + viewendorsements + "</td>";
                _mailBody += "</tr>";
            }

        }

        _mailBody += "</table>";
        _mailBody += "<br/><br/>You are also able to view this quote in detail through our Members Area by clicking on the link below. <br/><br/>";
        _mailBody += " <a href='http://www.comparexpress.com/car-insurance/login.aspx'>CompareXpress.com</a> <br/><br/>";

        //_mailBody += "Enter your Email and Password as follows: <br/>";

        //Account _account = new Account();
        //AccountDB _accountdb = new AccountDB();
        //_account = _accountdb.GetAccount(Convert.ToInt64(Session[General.UserId].ToString()));
        //if (_account != null)
        //{
        //    _mailBody += "<br /> User Name : " + Session[General.UserEmail].ToString();
        //    _mailBody += "<br /> Password : " + _account.AuthCode + "<br/><br/>";

        //}


        _mailBody += "</td></tr>";
        _mailBody += "<tr><td id='email_footer'><a href='http://www.comparexpress.com' target='_blank'><img src='" + _currentDomainUrl + "/images/email/footer_quote.png' alt='CompareXpress - Partners' width='596' height='174' border='0' /></a>";
        _mailBody += "</td></tr></table>";

        _mailBody += "<hr />";
        _mailBody += "This Quote is subject to the insurer's final confirmation and coverage is only effective when the <br/>";
        _mailBody += "insurer has accepted the risk.<br/>";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
        _mailBody += "<hr />";
        _mailBody += "</center></body>";

        if (MyMailManager.SendCARMessage(_emailTo, _emailSubject, _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private void SendCarInsuranceQuote(DataTable dtResult)
    {
        if (CheckFirstTimeQuote())
        {
            string _filename = GenerateGridResultPDF();
            if (!SendMailFirstQuoteToUser())
            {
                //Account _account = new Account();
                //AccountDB _accountdb = new AccountDB();
                //_account = _accountdb.GetAccount(Convert.ToInt64(Session[General.UserId].ToString()));
                //if (_account.Info1 == "0")
                //{
                //    _account.Info2 = "First Quote And " + _account.Info2;
                //}
                //else
                //{
                //    _account.Info1 = "0";
                //    _account.Info2 = "First Quote - Car Insurance";
                //}
            }
        }
    }

    private void SendCarInsuranceQuote()
    {
        if (CheckFirstTimeQuote())
        {
            if (!SendMailFirstQuoteToUser())
            {

            }
        }
    }

    private string GenerateGridResultPDF()
    {
        CarResultGridPDFOutput _resultPDF = new CarResultGridPDFOutput();
        _resultPDF.CarId = Session[General.CarId].ToString();
        _resultPDF.Title = "Car Insurance Quotes";
        _resultPDF.ResultGridTable = (DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]; ;
        _resultPDF.CustomerName = Session[General.UserName].ToString();
        _resultPDF.Email = Session[General.UserEmail].ToString();
        _resultPDF.Mobile = Session[General.UserPhoneNo].ToString();

        Profile _p = new Profile();
        ProfileDB _pdb = new ProfileDB();
        _p = _pdb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));
        if (_p != null)
        {
            _resultPDF.DOB = _p.DOB.ToString("dd/MMM/yyyy");
            _resultPDF.DriveYearSg = _p.YearDriveSg.ToString();
            _resultPDF.Gender = _p.Gender.ToString();
            _resultPDF.JobNature = _p.JobNature;
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("aTable");
            _dt = _db.GetDataTable("select M.Description AS MaritalStatus, O.Description AS Occupation, PRE.CompanyName AS CurrentInsurer from tblCEUsrProfile P" +
                                " INNER JOIN tblMaritalStatusInfo M ON P.MaritalStatus = M.MaritalStatusId" +
                                " INNER JOIN tblOccupationInfo O ON Cast(P.Occupation as Int) = O.OccupationId" +
                                " INNER JOIN tblCarDetail CD ON P.RefCEUserId = CD.RefCEUserId" +
                                " INNER JOIN tblPreInsurer PRE ON PRE.PreInsurerId = CAST(Cd.Info1 as Int)" +
                                " WHERE P.RefCEUserId = " + Session[General.UserId].ToString() + " And CD.CECarId = " + Session[General.CarId].ToString() + " And PRE.ServiceType = 100 And PRE.CompanyType = 1");

            if (_dt != null && _dt.Rows.Count > 0)
            {
                _resultPDF.MaritalStatus = _dt.Rows[0]["MaritalStatus"].ToString();
                _resultPDF.Occupation = _dt.Rows[0]["Occupation"].ToString();
                _resultPDF.CurrentInsurer = _dt.Rows[0]["CurrentInsurer"].ToString();
            }
        }

        CarDetail _cd = new CarDetail();
        CarDetailDB _cddb = new CarDetailDB();
        _cd = _cddb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), Convert.ToInt64(Session[General.UserId].ToString()));
        if (_cd != null)
        {
            _resultPDF.CarMakeModel = _cd.MakeModelDesc;
            _resultPDF.Offpeak = _cd.IsPeak ? "Yes" : "No";
            _resultPDF.ManfactYear = _cd.ManufactYear.ToString("0000");
            _resultPDF.RegYear = _cd.RegYear.ToString("0000");
        }

        CarPolicy _cp = new CarPolicy();
        CarPolicyDB _cpdb = new CarPolicyDB();
        _cp = _cpdb.GetCarPolicy(Convert.ToInt64(Session[General.CarId].ToString()), Convert.ToInt64(Session[General.UserId].ToString()));

        if (_cp != null)
        {
            _resultPDF.OFD = _cp.IsOffDriveCom ? "Yes" : "No";
            _resultPDF.CurrentNCD = _cp.NCDPercent.ToString() + "%";
            _resultPDF.AppNCD = _cp.Info1 + "%";
            _resultPDF.AnyClaim = _cp.IsClaimLastThreeYear ? "Yes" : "No";
            if (_cp.IsClaimLastThreeYear)
            {
                MyDatabase _db = new MyDatabase();
                DataTable _dt = new DataTable("aTable");
                _dt = _db.GetDataTable("SELECT (NOCLast1+NOCLast2+NOCLast3) ClaimCount," +
                                       " (CAST(NOCLast1Value as float) + CAST(NOCLast2Value as float) + CAST(NOCLast3Value as float)) ClaimAmount" +
                                       " FROM tblCarClaimHistory WHERE RefCEUserId = " + Session[General.UserId].ToString() + " And CECarId = " + Session[General.CarId].ToString());
                if (_dt != null && _dt.Rows.Count > 0)
                {
                    _resultPDF.AnyClaim = "Yes (Count:" + _dt.Rows[0]["ClaimCount"].ToString() + "/Amount:" + _dt.Rows[0]["ClaimAmount"].ToString() + ")";
                }
            }
            _resultPDF.AddDriver = _cp.IsAddDriver ? "Yes" : "No";
            _resultPDF.CommnecementDate = _cp.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            _resultPDF.QuoteDateTime = _cp.ModifiedDate.ToString("dd/MMM/yyyy hh:mm:ss tt");
        }
        _resultPDF.Footer = "For more information, please login to www.CompareXpress.com and view your save quotes.";
        return _resultPDF.GeneratePDF();
        //ExportGridView("CarInsuranceQuote", gvCarResult, "Car Insurance Quote");
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        //Response.Write(_dtResult.ToString());
        if (_dtResult.Rows.Count > 0)
        {
            //SendCarInsuranceQuote();
            imgInstantBuy.Visible = true;
            imgInstantBuy.ImageUrl = "~/images/bg/heading_buydirect.png";
            gvCarResult.Visible = true;
            divHeadingbuydirect.Visible = false; //Sakthi
            divUserRefDetail.Visible = false; //Sakthi

        }
        else
        {
            gvCarResult.Visible = false;
            bool isSubmitted = GetReferenceUser(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt64(Session[CE.Global.General.CarId].ToString()), "CI");
            divHeadingbuydirect.Visible = false;
            divUserRefDetail.Visible = true;
            imgbtnCompare.Visible = false;
            imgbtnCompare2.Visible = false;
            btnBack.Visible = false;
            imgup.Visible = false;
            imgdown.Visible = false;

            if (isSubmitted)
            {
                divNoMatchFound.Visible = false;
                //divNoInstantMatchFound.Visible = true;
                Response.Redirect("offline-quote.aspx");
            }
            else
            {
                if (CheckMailSendCount())
                {

                    if (CheckOfflineCommencementDate())
                    {
                        divNoMatchFound.Visible = false;
                        //divNoInstantMatchFound.Visible = true;
                        Response.Redirect("offline-quote.aspx");
                    }
                    else
                    {

                        divNoMatchFound.Visible = true;
                        //divNoInstantMatchFound.Visible = false;


                    }
                }
                else
                {
                    divNoMatchFound.Visible = true;

                    //divNoInstantMatchFound.Visible = false;
                }
            }
            //string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive").ToString();
            //if (isCXLive != "1")
            //{
            //    gvCarResult.Visible = false;
            //    GetReferenceUser(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt64(Session[CE.Global.General.CarId].ToString()),"CI");
            //    divHeadingbuydirect.Visible = false; //Sakthi
            //    divUserRefDetail.Visible = true; //Sakthi
            //}
            //else
            //{
            //    gvCarResult.Visible = true;
            //    divHeadingbuydirect.Visible = true; //Sakthi
            //    divUserRefDetail.Visible = false; //Sakthi
            //}
            imgInstantBuy.Visible = false;
            imgInstantBuy.ImageUrl = "~/images/bg/heading_buydirect_noresult.png";

        }
        Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;

    }

    protected void ibtRunNewQuote_Click(object sender, ImageClickEventArgs e)
    {
        CE.Global.General.ClearAllSession(this.Page, "AL");
        Response.Redirect("~/car-insurance/");
    }

    protected void btnNewQuote_Click(object sender, EventArgs e)
    {
        CE.Global.General.ClearAllSession(this.Page, "AL");
        Response.Redirect("~/car-insurance/");
    }

    protected void btnNewCarInsurance_Click(object sender, EventArgs e)
    {
        Session[General.CarId] = null;
        Session[General.CarPolicyId] = null;
        Session[General.CarMoreDetailId] = null;
        Session[General.CarResultId] = null;
        Session[General.CarClaimHistoryId] = null;

        string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive").ToString();

        Response.Redirect("~/car-insurance/");

        //if (isCXLive == "1")
        //    Response.Redirect("carandpolicy_details.aspx");
        //else
        //    Response.Redirect("carandpolicy_details2.aspx");

    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        //string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive").ToString();

        //if (isCXLive == "1")
        //    Response.Redirect("carandpolicy_details.aspx");
        //else
        //    Response.Redirect("CarandPolicy_Details2.aspx");

        //Response.Redirect("carandpolicy_details.aspx");
        Response.Redirect("profile.aspx");
    }

    protected void imgbtnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("profile.aspx");
    }

    protected void gvCarResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "~/Images/icons/clear.gif";
                        HtmlGenericControl gv = new HtmlGenericControl("div");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                imageSort.ImageUrl = "~/Images/icons/Sort_Down.gif";
                            }
                            else
                            {

                                imageSort.ImageUrl = "~/Images/icons/Sort_Up.gif";
                            }
                        }

                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }

            #region Custom Header
            ////Build custom header.
            //GridView oGridView = (GridView)sender;
            //GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            //TableCell oTableCell = new TableCell();

            ////Add Free Cell
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Free Cell
            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Free Cell
            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Personal Accident Cover
            //oTableCell = new TableCell();
            //oTableCell.Text = "Personal Accident Cover";
            //oTableCell.BorderStyle = BorderStyle.Solid;
            //oTableCell.BorderColor = System.Drawing.Color.Blue;
            //oTableCell.ColumnSpan = 2;
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Free Cell
            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Employee
            //oTableCell = new TableCell();
            //oTableCell.Text = "Loss of Use Benefit";
            //oTableCell.ColumnSpan = 2;

            //oTableCell.BorderStyle = BorderStyle.Solid;
            //oTableCell.BorderColor = System.Drawing.Color.Blue;
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;
            //oGridViewRow.Cells.Add(oTableCell);

            ////Add Free Cell
            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            ////Add Free Cell
            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            //oTableCell = new TableCell();
            //oTableCell.Text = "";
            //oGridViewRow.Cells.Add(oTableCell);
            ////oTableCell.BackColor = System.Drawing.Color.LightGray;
            //oTableCell.HorizontalAlign = HorizontalAlign.Center;

            //oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
            #endregion
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //e.Row.Attributes.Add("onmouseover", "javascript:orgBgColor = this.className; this.className = 'gridover';");
            //e.Row.Attributes.Add("onmouseout", "javascript:this.className = orgBgColor;");

            _currentRow += 1;
            e.Row.ID = "GridRow" + (_currentRow).ToString();
            //e.Row.CssClass = "GridRow" + (_currentRow).ToString();
            //e.Row.Attributes.Add("onclick", "javascript:alert('hello " + e.Row.ClientID.ToString() + "');");

            //controls_usrMoreInfoDropdownButton btnMoreInfo = (controls_usrMoreInfoDropdownButton)e.Row.FindControl("ibtMoreInfo");
            //ImageButton btnApplyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");




            //btnMoreInfo.RowId = "NewRow" + ((e.Row.RowIndex * 2) + 1).ToString();
            //btnApplyNow.CommandArgument = e.Row.RowIndex.ToString();

            //if (e.Row.DataItem != null)
            //{
            //    _currentRow += 1;
            //    btnApplyNow.ID = "BuyNow" + _currentRow.ToString();
            //    string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();
            //    //btnMoreInfo.MoreInfo = "<a href=\"" + btnMoreInfo.BenefitNavigateURL + _companyId + "\" target=\"_blank\">Benefits</a>&nbsp&nbsp" +
            //    //                        "<a href=\"" + btnMoreInfo.WorkShopNavigateURL + _companyId + "\" target=\"_blank\">Workshops</a><br/><br/>";
            //    if (_companyId == "30")
            //    {
            //        btnApplyNow.Attributes.Add("onmouseover", "this.src='/images/buttons/select_o.gif'; JT_showbuydirect('callout_etiqa.html?width=209', '" + btnApplyNow.ClientID + "', 'Testing');");
            //    }
            //    else
            //    {
            //        btnApplyNow.Attributes.Add("onmouseover", "this.src='/images/buttons/select_o.gif'; JT_showbuydirect('callout.html?width=209', '" + btnApplyNow.ClientID + "', 'Testing');");
            //    }
            //}
        }
    }

    protected void gvCarResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("BuyNow"))
        {

            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = gvCarResult.DataKeys[index];

            Session[CE.Global.General.CarResultId] = myData[0].ToString();
            Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            Int64 _companyId = Convert.ToInt64(myData[1].ToString());
            LogUserSelectHistory(_resultId, _companyId);

            System.Threading.Thread.Sleep(3000);
            if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 29)
            {
                Response.Redirect("~/car-insurance/proposalforms/liberty_proposal_form.aspx");
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 30)
            {
                Response.Redirect("~/car-insurance/proposalforms/etiqa_proposal_form.aspx");
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 23)
            {
                Response.Redirect("~/car-insurance/proposalforms/hsbc_proposal_form.aspx");
            }

        }

    }

    private void LogUserSelectHistory(Int64 ResultId, Int64 CompanyId)
    {
        UserSelectHistoryDB _userselectdb = new UserSelectHistoryDB();
        _userselectdb.LogUserSelectHistory("CI", Request.Browser.Type, Request.UserHostAddress, "CI", ResultId, CompanyId);
    }

    protected void gvCarResult_Sorting(object sender, GridViewSortEventArgs e)
    {
        SortGridViews(e.SortExpression);
    }

    private void SortGridViews(string strExpression)
    {
        if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] == null)
        {
            GetTempResultTableTwo();
        }

        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = SortDirection.Descending;
        }

        if (ViewState["SortExpression"] == null)
        {
            ViewState["SortExpression"] = SortDirection.Ascending.ToString();
        }

        DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        string strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        else
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }

        dv.Sort = strExpression + strSort;
        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    private void CarUserOptionLog(bool isBuyNow, bool isCallMe, bool isEmailMe)
    {
        CarUserOption caruseroption = new CarUserOption();
        CarUserOptionDB caruseroptiondb = new CarUserOptionDB();

        caruseroption.CarUserOptionId = 0;
        caruseroption.CECarId = Convert.ToInt64(Session[General.CarId].ToString());
        caruseroption.IsBuyNow = isBuyNow;
        caruseroption.IsCallMe = isCallMe;
        caruseroption.IsEmailMe = isEmailMe;
        caruseroption.IsEmailThis = false;
        caruseroption.RecipientName = "";
        caruseroption.RecipientEmailAddress = "";
        caruseroption.ViewedDetailId = 0;
        caruseroption.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());

        caruseroptiondb.Insert(caruseroption);
    }

    protected void gvCarResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();

            Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
            Label lblTempId = (Label)e.Row.FindControl("lblTempId");
            Label lblInsurerName = (Label)e.Row.FindControl("lblInsurerName");

            //string _logoUrl = DataBinder.Eval(e.Row.DataItem, "CompanyLogoUrl").ToString();

            string _logoUrl = "/images/public/logo/";

            if (_companyId == "23")
            {
                _logoUrl += "hsbc.png";
            }
            else if (_companyId == "29")
            {
                _logoUrl += "liberty.png";
            }
            else if (_companyId == "30")
            {
                _logoUrl += "etiqa.png";                
            }

            imgCompanyLogo.ImageUrl = _logoUrl;
            imgCompanyLogo.ToolTip = DataBinder.Eval(e.Row.DataItem, "InsurerName").ToString(); ;
            lblTempId.Text = DataBinder.Eval(e.Row.DataItem, "CITempResultId").ToString();

            string _companyName = "";

            if (_companyId != "29")
            {
                lblInsurerName.Text = DataBinder.Eval(e.Row.DataItem, "InsurerName").ToString() + " Insurance";
            }
            else
            {
                lblInsurerName.Text = DataBinder.Eval(e.Row.DataItem, "InsurerName").ToString();
            }

            if (_companyId == "23")
            {
                _companyName = "HSBC Insurance";
            }
            else if (_companyId == "29")
            {
                _companyName = "Liberty Insurance";
            }
            else if (_companyId == "30")
            {
                _companyName = "Etiqa Insurance";
            }

            Button btnLearnMore = (Button)e.Row.FindControl("btnLearnMore");
            btnLearnMore.CommandArgument = e.Row.RowIndex.ToString();

            btnLearnMore.OnClientClick = "javascript:void(0);ShowPopup('" + _companyId + "', '" + lblTempId.Text + "', '" + _companyName + "');return false;";

            //check call me status
            string _providerID = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();

            if ((Session[General.AgentId] == null)
               && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
               Convert.ToInt32(CE.Global.CEUserType.Customer))
            {
                ContactUser _cu = new ContactUser();
                ContactUserDB _cudb = new ContactUserDB();


                if (_providerID.ToString() == "29")
                {
                    _cu = _cudb.GetCallMe(Convert.ToInt64(Session[General.UserId].ToString()), Convert.ToInt64(Session[General.CarId].ToString()), "CI", 29);
                }
                else if (_providerID.ToString() == "30")
                {
                    _cu = _cudb.GetCallMe(Convert.ToInt64(Session[General.UserId].ToString()), Convert.ToInt64(Session[General.CarId].ToString()), "CI", 30);
                }

                if (_cu != null)
                {
                    if (_cu.ProviderCompanyId == 29)
                    {
                        inputLibertyCallMeDone.Value = "1";
                    }
                    else if (_cu.ProviderCompanyId == 30)
                    {
                        inputEtiqaCallMeDone.Value = "1";
                    }

                }
            }
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "";
            e.Row.Cells[1].Text = "";
            e.Row.Cells[2].Text = "";
            e.Row.Cells[3].Text = "";
            e.Row.Cells[4].Text = "";
            e.Row.Cells[5].Text = "";
            e.Row.Cells[6].Text = "";
        }
    }

    protected void imgbtnCompare_Click(object sender, ImageClickEventArgs e)
    {
        string sQueryString = "";
        bool isChecked;
        foreach (GridViewRow vRow in gvCarResult.Rows)
        {
            isChecked = ((CheckBox)vRow.FindControl("cbCarSelect")).Checked;
            if (isChecked)
            {
                string skey = ((Label)vRow.FindControl("lblTempId")).Text;
                sQueryString += skey + ",";
            }
        }

        Session["CarSelected"] = sQueryString;

        Response.Redirect("results-details.aspx");
    }

    protected void btnCompare_Click(object sender, EventArgs e)
    {
        string sQueryString = "";
        bool isChecked;
        foreach (GridViewRow vRow in gvCarResult.Rows)
        {
            isChecked = ((CheckBox)vRow.FindControl("cbCarSelect")).Checked;
            if (isChecked)
            {
                string skey = ((Label)vRow.FindControl("lblTempId")).Text;
                sQueryString += skey + ",";
            }
        }

        Session["CarSelected"] = sQueryString;


        Response.Redirect("results-details.aspx");
    }

    protected void btnBuyNow_Click(object sender, EventArgs e)
    {
        string _providerID = "";
        _providerID = inputProviderId.Value.Trim();

        Session[CE.Global.General.CarResultId] = inputCarResultId.Value.Trim();
        Session[CE.Global.General.ProviderCompanyId] = _providerID;
        Session["FromSummary"] = "1";
        CarUserOptionLog(true, false, false);

        if (_providerID == "23")
        {
            Response.Redirect("~/car-insurance/proposalforms/hsbc_proposal_form.aspx");
        }
        else if (_providerID == "29")
        {
            Response.Redirect("~/car-insurance/proposalforms/liberty_proposal_form.aspx");
        }
        else if (_providerID == "30")
        {
            Response.Redirect("~/car-insurance/proposalforms/etiqa_proposal_form.aspx");
        }
    }

    protected void btnCallMe_Click(object sender, EventArgs e)
    {
        string _providerID = "";
        _providerID = inputProviderId.Value.Trim();

        Session[CE.Global.General.CarResultId] = inputCarResultId.Value.Trim();
        Session[CE.Global.General.ProviderCompanyId] = _providerID;

        if ((Session[General.AgentId] == null)
                && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Customer))
        {
            ContactUser _cu = new ContactUser();
            ContactUserDB _cudb = new ContactUserDB();


            if (_providerID.ToString() == "29")
            {
                _cu = _cudb.GetCallMe(Convert.ToInt64(Session[General.UserId].ToString()), Convert.ToInt64(Session[General.CarId].ToString()), "CI", 29);
            }
            else if (_providerID.ToString() == "30")
            {
                _cu = _cudb.GetCallMe(Convert.ToInt64(Session[General.UserId].ToString()), Convert.ToInt64(Session[General.CarId].ToString()), "CI", 30);
            }

            if (_cu != null)
            {
                if (_cu.ProviderCompanyId == 29)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "Alert", "alert('You have already requested for Liberty Insurance to call you.'  + '\\r\\n' + 'Please wait a while to get call from them. Thank you.')", true);
                }
                else if (_cu.ProviderCompanyId == 30)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "Alert", "alert('You have already requested for Etiqa Insurance to call you.'  + '\\r\\n' + 'Please wait a while to get call from them. Thank you.')", true);
                }

            }
            else
            {
                if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.CarId] != null)
                {
                    string _message = "";
                    string _title = "";
                    string _ec = "";
                    txtFullName.Text = General.ClearScriptTag(txtFullName.Text);
                    _message = "Customer Name: " + txtFullName.Text;
                    _title = "Call Me request by " + txtFullName.Text + " for " + inputCallMeCompanyName.Value;
                    //ChangeValidationEffectServerSide("callme");
                    if (IsValid)
                    {
                        Int64 _result = 0;
                        ContactUser _contactuser = new ContactUser();
                        ContactUserDB _contactuserdb = new ContactUserDB();

                        _contactuser.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                        _contactuser.ProductId = Convert.ToInt64(Session[General.CarId].ToString());

                        if (_providerID == "29")
                        {
                            _contactuser.ProviderCompanyId = 29;
                            _ec = "1029";
                        }
                        else if (_providerID == "30")
                        {
                            _contactuser.ProviderCompanyId = 30;
                            _ec = "1030";
                        }
                        _contactuser.InsuranceType = "CI";
                        _contactuser.FullName = txtFullName.Text.Trim();
                        _contactuser.ContactNo = txtMobileNo.GetPhoneNo();
                        _contactuser.CallTime = Convert.ToInt16(ddlCallMeTime.Text);
                        _contactuser.AgentId = 0;
                        _contactuser.Status = true;

                        _result = _contactuserdb.Insert(_contactuser);
                        if (_result > 0)
                        {
                            //Sakthi on 29 Jun 2011 (Alternative mail sending) -- Start
                            CXAgent _cxagent = new CXAgent();
                            CXAgentDB _cxagentdb = new CXAgentDB();
                            Int64 _ProductId = 0;
                            Int64 _AgentId = 0;
                            Int64 _CEID = Convert.ToInt64(Session[General.UserId].ToString());
                            string _AgentName = "";
                            string _AgentEmail = "";
                            string _CCEmail = "";
                            string _BCCEmail = "";
                            DataTable _dtCXAgent = _cxagentdb.GetCXAgentList(_CEID, "CM", 0);
                            if (_dtCXAgent != null && _dtCXAgent.Rows.Count > 0)
                            {
                                _AgentId = Convert.ToInt64(_dtCXAgent.Rows[0]["AgentId"].ToString());
                                _AgentName = _dtCXAgent.Rows[0]["AgentName"].ToString();
                                _AgentEmail = _dtCXAgent.Rows[0]["Email"].ToString();

                                _ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                                _contactuserdb.Update(_CEID, _AgentId, _contactuser.ProviderCompanyId, "CM", _ProductId);

                                _message += "<br/><br/>Make/Model : " + inputCallMeMakeModel.Value;
                                _message += "<br/><br/><b>Insurer : <span style='color:#f00'>" + inputCallMeCompanyName.Value;
                                _message += "</span></b><br/><br/>Contact No : " + txtMobileNo.GetPhoneNo();
                                _message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                                _message += "<br/><br/>Agent Name : " + _AgentName;
                                //string _emailList = ConfigurationManager.AppSettings["CICallMeMessageReceiver"].ToString();
                                //MyMailManager.SendCRMMessage(_emailList, _title, _message);
                                _CCEmail = ConfigurationManager.AppSettings["CC_CICallMeMessageReceiver"].ToString();
                                _BCCEmail = ConfigurationManager.AppSettings["BCC_CICallMeMessageReceiver"].ToString();
                                MyMailManager.SendCallMeMessage(_AgentEmail, _CCEmail, _BCCEmail, _title, _message);

                                CarUserOptionLog(false, true, false);

                                Response.Redirect("~/user/usermessage.aspx?mt=CI&ec=" + _ec);
                            }
                            //Sakthi on 29 Jun 2011 (Alternative mail sending) -- End
                        }
                    }
                }
            }

        }

    }

    protected void btnEmailMe_Click(object sender, EventArgs e)
    {
        string _providerID = "";
        _providerID = inputProviderId.Value.Trim();

        Session[CE.Global.General.CarResultId] = inputCarResultId.Value.Trim();
        Session[CE.Global.General.ProviderCompanyId] = _providerID;

        string _ec = "";

        if (_providerID == "23")
        {
            _ec = "1123";
        }
        else if (_providerID == "29")
        {
            _ec = "1129";
        }
        else if (_providerID == "30")
        {
            _ec = "1130";
        }

        if (SendMailToUserNEW())
        {
            CarUserOptionLog(false, false, true);
            Session["FromSummary"] = "1";
            //Response.Redirect("~/user/usermessage.aspx?mt=CI&ec=" + _ec);
            Response.Redirect("email-usermessage.aspx");
        }



    }

    protected void btnEmailThis_Click(object sender, EventArgs e)
    {
        string _providerID = "";
        _providerID = inputProviderId.Value.Trim();

        Session[CE.Global.General.CarResultId] = inputCarResultId.Value.Trim();
        Session[CE.Global.General.ProviderCompanyId] = _providerID;
        Session["FromSummary"] = "1";

        Response.Redirect("email-this.aspx");

    }

}
